package org.person.test.intercepter;

import org.person.basic.annotation.MyAnnotation;
import org.person.basic.data.ContextMap;
import org.person.org.domain.Employee;
import org.person.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private IEmployeeService employeeService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // false 为拦截 true为放行
        System.out.println("===========================警告！非法请求！==============================");
        // 获取前端的token 从header中获取请求
        String token = request.getHeader("token");
        if (Objects.isNull(token)){
            // 没有登录应该被拦截
            response.getWriter().print("{\"success\":false,\"msg\":\"noLogin\"}");
            return false;
        }
        // 根据token获取map中的对象
        Employee employee = ContextMap.loginMap.get(token);
        if (Objects.isNull(employee)){
            // 没有登录应该被拦截
            response.getWriter().print("{\"success\":false,\"msg\":\"noLogin\"}");
            return false;
        }

        // 鉴权
        // 1. 判断访问资源是否需要权限 - 判断请求的方法是否有权限注解
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
        if (Objects.nonNull(annotation)){
            // 2. 如果需要权限
            // 3. 获取用户权限
            // 根据用户的id 查询 角色id 在查 角色拥有的权限
            List<String> permissions = employeeService.queryPermissionsById(employee.getId());
            // 4. 获取资源权限
            String name = method.getName();
            String simpleName = handlerMethod.getBeanType().getSimpleName();
            String resourceUrl = simpleName +":"+name;

            // 5. 判断用户权限是否包含资源权限
            boolean contains = permissions.contains(resourceUrl);
            if(!contains){
                response.getWriter().print("{\"success\":false,\"msg\":\"noPermission\"}");
                return false;
            }
        }
        return true;
    }
}
